package com.fly.core;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * Dao实现类 - Dao实现类基类
 */
@Slf4j
@Component
@SuppressWarnings({"unchecked", "rawtypes", "hiding", "unused", "deprecation"})
public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>
{
    private Class<T> entityClass;
    
    @Autowired
    protected SessionFactory sessionFactory;
    
    @Autowired
    private HibernateTemplate hibernateTemplate;
    
    public BaseDaoImpl()
    {
        this.entityClass = null;
        Class c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType)
        {
            Type[] parameterizedType = ((ParameterizedType)type).getActualTypeArguments();
            this.entityClass = (Class<T>)parameterizedType[0];
        }
    }
    
    protected Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
    
    @Override
    public T get(PK id)
    {
        return getSession().get(entityClass, id);
    }
    
    @Override
    public T load(PK id)
    {
        return getSession().load(entityClass, id);
    }
    
    /**
     * 根据hql语句获取集合
     * 
     * @return
     */
    @Override
    public List<T> getList(String hql)
    {
        return getSession().createQuery(hql).list();
    }
    
    @Override
    public List<T> get(PK[] ids)
    {
        String hql = "from " + entityClass.getName() + " as model where model.id in(:ids)";
        Query q = getSession().createQuery(hql).setParameterList("ids", ids);
        return q.list();
    }
    
    /**
     * 根据HQL语句查询数据
     * 
     * @return
     */
    @Override
    public List<T> executeQuery(String hql)
    {
        return getSession().createQuery(hql).list();
    }
    
    @Override
    public T get(String propertyName, Object value)
    {
        String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
        List<T> t = getSession().createQuery(hql).setParameter(0, value).list();
        if (!t.isEmpty())
        {
            return t.get(0);
        }
        return null;
    }
    
    @Override
    public T get(Map<String, Object> propertyMap)
    {
        String hql = "from " + entityClass.getName() + " as model where ";
        Iterator<String> keyIterator = propertyMap.keySet().iterator();
        List<String> keyArr = new ArrayList<String>(propertyMap.size());
        String key = keyIterator.next();
        keyArr.add(key);
        hql += "model." + key + " = ?";
        while (keyIterator.hasNext())
        {
            key = keyIterator.next();
            keyArr.add(key);
            hql += " and model." + key + " = ?";
        }
        Query q = getSession().createQuery(hql);
        for (int i = 0; i < keyArr.size(); i++)
        {
            q.setParameter(i, propertyMap.get(keyArr.get(i)));
        }
        return (T)q.uniqueResult();
    }
    
    @Override
    public List<T> getList(String propertyName, Object value)
    {
        String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
        Query q = getSession().createQuery(hql).setParameter(0, value);
        return q.list();
    }
    
    /**
     * 根据条件查询。条件为propertyName!=value
     **/
    @Override
    public List<T> getNoList(String propertyName, Object value)
    {
        String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " != ?";
        Query q = getSession().createQuery(hql).setParameter(0, value);
        return q.list();
    }
    
    @Override
    public List<T> getAll()
    {
        String hql = "from " + entityClass.getName();
        List<T> list = null;
        try
        {
            list = getSession().createQuery(hql).list();
        }
        catch (HibernateException e)
        {
            log.error(e.getMessage(), e);
        }
        return list;
    }
    
    public List<T> getAll(String hql)
    {
        List<T> list = null;
        try
        {
            list = getSession().createQuery(hql).list();
        }
        catch (HibernateException e)
        {
            log.error(e.getMessage(), e);
        }
        return list;
    }
    
    @Override
    public Long getTotalCount()
    {
        String hql = "select count(*) from " + entityClass.getName();
        return (Long)getSession().createQuery(hql).uniqueResult();
    }
    
    @Override
    public Long getTotalCountGroupByProerty(String groupByName)
    {
        String hql = "select count(*) from " + entityClass.getName() + " group by ?";
        return (Long)getSession().createQuery(hql).setParameter(0, groupByName).uniqueResult();
    }
    
    @Override
    public Long getTotalCount(String propertyName, Object value)
    {
        String hql = "select count(*) from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
        return (Long)getSession().createQuery(hql).setParameter(0, value).uniqueResult();
    }
    
    @Override
    public Double getSumTotal(String propertySum)
    {
        String hql = "select sum(" + propertySum + ") from " + entityClass.getName();
        return (Double)getSession().createQuery(hql).uniqueResult();
    }
    
    @Override
    public Double getSumTotal(String propertySum, String propertyName, Object value)
    {
        String hql = "select sum(" + propertySum + ") from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
        return (Double)getSession().createQuery(hql).setParameter(0, value).uniqueResult();
    }
    
    @Override
    public boolean isUnique(String propertyName, Object oldValue, Object newValue)
    {
        if (newValue == oldValue || newValue.equals(oldValue))
        {
            return true;
        }
        if (newValue instanceof String)
        {
            if (oldValue != null && StringUtils.equalsIgnoreCase((String)oldValue, (String)newValue))
            {
                return true;
            }
        }
        T object = get(propertyName, newValue);
        return (object == null);
    }
    
    @Override
    public boolean isExist(String propertyName, Object value)
    {
        T object = get(propertyName, value);
        return (object != null);
    }
    
    @Override
    public PK save(T entity)
    {
        return (PK)getSession().save(entity);
    }
    
    @Override
    public void update(T entity)
    {
        getSession().update(entity);
    }
    
    @Override
    public void merge(T entity)
    {
        getSession().merge(entity);
    }
    
    @Override
    public void delete(T entity)
    {
        getSession().delete(entity);
    }
    
    @Override
    public void delete(PK id)
    {
        T entity = load(id);
        getSession().delete(entity);
    }
    
    @Override
    public void delete(PK[] ids)
    {
        for (PK id : ids)
        {
            T entity = load(id);
            getSession().delete(entity);
        }
    }
    
    @Override
    public void flush()
    {
        getSession().flush();
    }
    
    @Override
    public void clear()
    {
        getSession().clear();
    }
    
    @Override
    public void evict(Object object)
    {
        getSession().evict(object);
    }
    
    @Override
    public Long getTotalCount(String propertyName, Object value, String whereName, Object whereObject)
    {
        String hql = "select count(*) from " + entityClass.getName() + " as model where model." + propertyName + " = ? and model." + whereName + " = ?";
        return (Long)getSession().createQuery(hql).setParameter(0, value).setParameter(1, whereObject).uniqueResult();
    }
    
    @Override
    public List<T> getList(Map<String, Object> propertyMap)
    {
        String hql = "from " + entityClass.getName() + " as model where ";
        Iterator<String> keyIterator = propertyMap.keySet().iterator();
        List<String> keyArr = new ArrayList<String>(propertyMap.size());
        String key = keyIterator.next();
        keyArr.add(key);
        hql += "model." + key + " = ?";
        while (keyIterator.hasNext())
        {
            key = keyIterator.next();
            keyArr.add(key);
            hql += " and model." + key + " = ?";
        }
        Query q = getSession().createQuery(hql);
        for (int i = 0; i < keyArr.size(); i++)
        {
            q.setParameter(i, propertyMap.get(keyArr.get(i)));
        }
        return q.list();
    }
    
    @Override
    public List<T> getNoList(Map<String, Object> propertyMap)
    {
        String hql = "from " + entityClass.getName() + " as model where ";
        Iterator<String> keyIterator = propertyMap.keySet().iterator();
        List<String> keyArr = new ArrayList<String>(propertyMap.size());
        String key = keyIterator.next();
        keyArr.add(key);
        hql += "model." + key + " != ?";
        while (keyIterator.hasNext())
        {
            key = keyIterator.next();
            keyArr.add(key);
            hql += " and model." + key + " != ?";
        }
        Query q = getSession().createQuery(hql);
        for (int i = 0; i < keyArr.size(); i++)
        {
            q.setParameter(i, propertyMap.get(keyArr.get(i)));
        }
        return q.list();
    }
    
    @Override
    public T like(String propertyName, Object value)
    {
        String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " like '%" + value.toString() + "%'";
        return (T)getSession().createQuery(hql).uniqueResult();
    }
    
    public <T> Criteria createCriteria(Class<T> entityClass)
    {
        return getSession().createCriteria(entityClass);
    }
    
    /**
     * @param <T>
     * @param entityClass
     * @return 通过字节码得到实体名；
     */
    protected <T> String getEntityName(Class<T> entityClass)
    {
        String queryName = null;
        Entity entity = entityClass.getAnnotation(Entity.class);
        if (entityClass != null)
        {
            queryName = entityClass.getName();
        }
        return queryName;
    }
    
    public int countRecord(String hql)
    {
        return Integer.parseInt(executeQuery(hql).get(0).toString());
    }
    
    /**
     * 加入条件的获取数据
     * 
     * @param object
     * @param whereStr
     * @param orderbyStr
     * @param groupByStr
     * @return
     */
    @Override
    public List find(Class object, String filedName, String whereStr, String orderbyStr, String groupByStr)
    {
        StringBuilder jpql = new StringBuilder();
        if (StringUtils.isNotBlank(filedName) && filedName == "*")
        {
            jpql.append("select a from " + getEntityName(object) + " a ");
        }
        else if (StringUtils.isNotBlank(filedName) && filedName != "*")
        {
            jpql.append("select a." + filedName + " from " + getEntityName(object) + " a ");
        }
        if (StringUtils.isNotBlank(whereStr))
        {
            jpql.append("where  a." + whereStr);
        }
        if (StringUtils.isNotBlank(orderbyStr))
        {
            jpql.append(" order by   a." + orderbyStr);
        }
        if (StringUtils.isNotBlank(groupByStr))
        {
            jpql.append(" group by   a." + groupByStr);
        }
        return executeQuery(jpql.toString());
    }
    
    @Override
    public Long getTotalCount(Map<String, Object> propertyMap)
    {
        String hql = "select count(1) from " + entityClass.getName() + " as model where ";
        Iterator<String> keyIterator = propertyMap.keySet().iterator();
        List<String> keyArr = new ArrayList<String>(propertyMap.size());
        String key = keyIterator.next();
        keyArr.add(key);
        hql += "model." + key + " = ?";
        while (keyIterator.hasNext())
        {
            key = keyIterator.next();
            keyArr.add(key);
            hql += " and model." + key + " = ?";
        }
        return (Long)getSession().createQuery(hql).uniqueResult();
    }
    
    @Override
    public List findBySql(String sql)
    {
        List list = null;
        try
        {
            list = getSession().createSQLQuery(sql).list();
        }
        catch (HibernateException e)
        {
            log.error(e.getMessage(), e);
        }
        return list;
    }
    
    @Override
    public int findTotalSQL(String hql)
    {
        int numb = 0;
        List li = getSession().createSQLQuery(hql).list();
        BigInteger obj = (BigInteger)li.get(0);
        if (obj != null && !obj.equals("") && !obj.equals("null"))
        {
            numb = obj.intValue();
        }
        return numb;
    }
}